package com.zzyq.pc.utils;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.zzyq.pc.common.StandardDataFormat;

public class HttpUtils {
    // 登录页面
    public static final String LOGIN_URL = "/views/index.jsp";
    // 首页
    public static final String MAIN_URL = "/views/admin.jsp";

    /**
     * 是否是Ajax请求
     * 
     * @param request
     * @return
     */
    public static boolean isAjax(ServletRequest request) {
        return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
    }

    /**
     * 避免代码冗余，在这封装一个方便组装返回信息的方法
     */
    public static String formatData(StandardDataFormat format, Integer code, String message, Object data) {
        format.setReturnCode(code);
        format.setReturnMessage(message);
        format.setReturnData(data);
        return JsonUtils.toString(format, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * response 输出JSON
     * 
     * @param hresponse
     * @param resultMap
     * @throws IOException
     */
    public static void out(ServletResponse response, String str) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charSet=UTF-8");
            out = response.getWriter();
            out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }
}
